// src/utils/fetchUtil.ts
import { ApiResponse } from '@/types/ApiResponse';

class FetchUtil {
  /**
   * Sends a POST request
   * @param url The URL of the request
   * @param body The request body data
   * @param headers Custom request headers (optional)
   * @returns A Promise that resolves to the response data
   */
  static post<TResponse, TBody>(
    url: string,
    body: TBody,
    headers: Record<string, string> = {}
  ): Promise<ApiResponse<TResponse>> {
    return new Promise((resolve, reject) => {
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json', // Default Content-Type
          ...headers // Merge custom headers
        },
        body: JSON.stringify(body) // Convert body to JSON string
      })
        .then((response) => {
          if (!response.ok) {
            reject(new Error(`HTTP error! status: ${response.status}`));
          }
          return response.json();
        })
        .then((data: ApiResponse<TResponse>) => resolve(data)) // Resolve with typed data
        .catch((error) => {
          console.error('Error in POST request:', error);
          reject(error); // Pass the error to the caller
        });
    });
  }
}

export default FetchUtil;